package com.allwees.core.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;

/**
 * xml <-> obj 转换工具
 *
 * @author yangylsky
 *
 */
@Slf4j
public class XmlUtil {
	private XmlUtil() {
	}

	/**
	 * add by scy 通过JAXB生成XML字符串
	 *
	 * @param obj
	 * @return
	 */
	public static String obj2Xml(Object obj) {
		try {
			// 利用jdk中自带的转换类实现
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			// 格式化xml输出的格式
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
			// 将对象转换成输出流形式的xml
			StringWriter sw = new StringWriter();
			marshaller.marshal(obj, sw);
			return sw.toString();
		} catch(JAXBException e) {
			log.error("", e);
			return "";
		}
	}

	/**
	 * add by scy 通过JAXB将XML转化为Object
	 *
	 * @param xml
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T xml2Obj(String xml, Class<T> clazz) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            StringReader reader = new StringReader(xml);
            T message = (T) unmarshaller.unmarshal(reader);
            return message;
        } catch (JAXBException e) {
			log.error("", e);
			return null;
        }
	}
}
